﻿using MPic.Business.BLL;
using MPic.Business.Entity;
using MPic.Business.Enums;
using MPic.Business.Models.QiNiu;
using MPic.Common;
using MPic.Filters;
using MPic.Utility;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MPic.Controllers
{
    [RoutePrefix("upload")]
    public class UploadController : BaseController
    {
        /// <summary>
        /// 当前站点地址
        /// </summary>
        private static string SiteUrl = ConfigurationManager.AppSettings["SiteUrl"];
        /// <summary>
        /// 允许上传图片类型
        /// </summary>
        private static string[] fileTypes = { "image/gif", "image/png", "image/jpeg", "image/jpg", "image/bmp", "image/webp" };

        [HttpPost, ExcUserAuth]
        [Route("images")]
        public ActionResult Images()
        {
            try
            {
                var ImgUrl = string.Empty;
                if (!User.Identity.IsAuthenticated)
                {
                    srm.code = ErrorCode.UploadFail.ToInt();
                    throw new InvalidOperationException("未登录.");
                }
                HttpPostedFileBase file = ((HttpRequestWrapper)Request).Files[0];
                if (!fileTypes.Contains(file.ContentType))
                {
                    srm.code = ErrorCode.UploadFail.ToInt();
                    throw new InvalidOperationException("图片格式不正确.");
                }
                if (file.ContentLength > (4 * 1048576))
                {
                    srm.code = ErrorCode.UploadFail.ToInt();
                    throw new InvalidOperationException("图片大小超过限制(4M).");
                }
                var curUser = new CurrentUser().Users;
                var qiniu = QiNiuBLL.Instance.GetByUserId(curUser.UserId);
                if (qiniu == null)
                {
                    if (curUser.UploadTimes > 30)
                    {
                        srm.code = ErrorCode.UploadFail.ToInt();
                        throw new InvalidOperationException("体验版暂时只支持30张图片上传哦，想要无限量上传请前往配置七牛云吧");
                    }
                }
                //图片相对地址
                string relativeDirPath = $"/u/{curUser.UserId}/";
                //图片存放目录
                string dirPath = System.Web.Hosting.HostingEnvironment.MapPath(relativeDirPath);
                //图片具体路径
                string ymd = $"{DateTime.Now.ToString("yyyy")}/{DateTime.Now.ToString("MM")}/{DateTime.Now.ToString("dd")}";
                dirPath += ymd + "/";
                relativeDirPath += ymd + "/";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                //图片名称
                var fileName = Guid.NewGuid().ToString("N").Substring(6, 8) + ".png";
                //图片在服务器路径
                var filePath = Path.Combine(dirPath, fileName);
                //保存图片
                file.SaveAs(filePath);
                if (qiniu != null && curUser.DefaultUploadType.Equals(UploadTypeEnum.QiNiu.ToInt()))
                {
                    fileName = QiNiuUploadHelper.Upload(qiniu, fileName, filePath);
                    if (string.IsNullOrEmpty(fileName))
                    {
                        srm.code = ErrorCode.UploadFail.ToInt();
                        throw new InvalidOperationException("上传七牛失败，请检查配置是否有误.");
                    }
                    ImgUrl = $"{qiniu.DomainName}/{fileName}";
                    //删除服务器文件
                    Task.Factory.StartNew(() =>
                    {
                        System.IO.File.Delete(filePath);
                    });
                }
                else
                {
                    ImgUrl = SiteUrl + relativeDirPath + fileName;
                }
                //上传信息写入数据库
                Task.Factory.StartNew(() =>
                {
                    FilesBLL.Instance.Insert(curUser.UserId, curUser.DefaultAlbum, ImgUrl, file.ContentLength.ToString(), fileName);
                });
                srm.data = ImgUrl;
            }
            catch (InvalidOperationException e)
            {
                srm.msg = e.Message;
            }
            catch (Exception e)
            {
                srm.code = ErrorCode.BusySystem.ToInt();
                srm.msg = ErrorCode.BusySystem.Description();
                LoggerHelper.Log("【Upload】->【images】", e);
            }
            return Result(srm);
        }
    }
}